package client.handler;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.MessageContext.Scope;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * SOAP Handler for setting the replyTo address in a portable way.
 * 
 */
public class ClientHandler implements SOAPHandler<SOAPMessageContext> {

	public boolean handleMessage(SOAPMessageContext context) {
		Boolean isOutbound = (Boolean) context
				.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
		
		try {
			SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
			SOAPHeader header = envelope.getHeader();
		
			if (isOutbound) {
			
				/* extract the generated MessageID */
				String messageID = getMessageID(header);
				context.put("MessageID", messageID);
				context.setScope("MessageID", Scope.APPLICATION);
	
				/* Cambia la dirección de respuesta. En el contexto esta almacenada la dirección donde fue publicado el servicio CallBackDinamic */
				setReplyTo(header,(String) context.get("ReplyTo"));
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}


		return true;
	}

	protected void setReplyTo(SOAPHeader header, String address) {
		/* change ReplyTo address using DOM */
		NodeList nodeListReplyTo = header.getElementsByTagName("ReplyTo");
		NodeList nodeListAddress = nodeListReplyTo.item(0).getChildNodes();
		for (int i = 0; i < nodeListAddress.getLength(); i++) {
			Node node = nodeListAddress.item(i);
			if ("Address".equals(node.getLocalName())) {
				node.setTextContent(address);
				break;
			}
		}
	}

	protected String getMessageID(SOAPHeader header) {
		NodeList nodeListMessageId = header.getElementsByTagName("MessageID");
		return nodeListMessageId.item(0).getTextContent();
	}

	@Override
	public void close(MessageContext context) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}
	
}
